<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div>
    <div class="search" style="height: 64px">
      <el-form :inline="true" :model="searchData">
        <el-form-item label="点位搜索:">
          <el-input v-model="searchData.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="区域搜索:">
          <el-select v-model="searchData.region" placeholder="请选择">
            <el-option v-for="item in list" :key="item.id" :label="item.region.name" :value="item.regionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="onSubmit"
            ><i class="el-icon-search"></i> 查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 下面的大盒子 -->
    <div class="result">
      <div class="operation">
        <!-- 头部 -->
        <el-button @click="openDrawer('add')">
          <i class="el-icon-circle-plus-outline"></i> 新建
        </el-button>
      </div>
      <!-- 列表 -->
      <el-table :data="list" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="点位名称"
          width="180"
        ></el-table-column>
        <el-table-column prop="region.name" label="所在区域"> </el-table-column>
        <el-table-column prop="businessType.name" label="商圈类型"> </el-table-column>
        <el-table-column prop="ownerName" label="合作商"> </el-table-column>
        <el-table-column prop="addr" label="详细地址">
         <template slot-scope="scope"> {{scope.row.addr.slice(12)}} </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <!--  #default="{ row }" => v-slot="{ row }" -->
          <template #default="{ row }">
            <div class="actions">
              <span @click="views(row.id)">查看详情</span>
              <span @click="edit(row)">修改</span>
              <span @click="del(row.id)" class="red">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <!-- 左边 -->
        <div class="text">
          共 {{ total }} 条数据 第{{ regionData.pageIndex }}/{{ totalPage }}页
        </div>
        <!-- 右边按钮 -->
        <div class="btn">
          <button type="button" @click="pre">上一页</button>
          <button @click="next">下一页</button>
        </div>
      </div>
    </div>
    <!--新增和修改 弹出层 -->
    <el-dialog
      v-if="!(this.drawerType==='views')"
      :title="drawerTitle"
      :visible.sync="visible"
      width="50%"
      @close="closeFn"
    >
    <!-- :rules="formRules"  item绑定规则prop="regionName"-->
      <el-form ref="diaForm" label-width="auto" label-position="right" :model="formData" :rules="formRules" >
        <el-form-item label="点位名称:" prop="name" >
          <el-input v-model="formData.name" placeholder="请输入" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="所在区域:" prop="regionId">
          <el-select  v-model="formData.regionId" placeholder="请选择" style="width: 80%">
            <!-- 输出的是value值 -->
            <el-option v-for="item in RegionList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属商圈:" prop="businessId">
          <el-select v-model="formData.businessId" placeholder="请选择" style="width: 80%">
            <el-option  v-for="item in BusinessList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商:" prop="ownerName">
          <el-select v-model="formData.ownerId" placeholder="请选择" style="width: 80%">
            <el-option v-for="item in PartnerList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址:" prop="areaCode">
           <el-cascader
           :options='options'
           v-model='formData.areaCode'
           @change='handleChange'
           :props="{ value: 'label' }"
           placeholder="省/市/区"
           style="width: 80%"></el-cascader>
        </el-form-item>
        <el-form-item prop="addr" >
          <el-input v-model="formData.addr" :autosize="{ minRows: 3, maxRows: 8 }"  maxlength="40"
           style="width: 80%" placeholder="请输入详细地址(不能超过40个字)"
            type="textarea" :rows="3"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="!(drawerType === 'views')">
        <el-button @click="closeFn">取 消</el-button>
        <el-button
          style="
            background: linear-gradient(135deg, #ff9743, #ff5e20);
            color: #fff;
            font-size: 16px;
          "
          @click="submit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <el-dialog v-if="this.drawerType==='views'" :title="drawerTitle"  :visible.sync="visible">
      <el-table :data="diaList">
        <el-table-column type="index" label="序号" width="150"></el-table-column>
        <el-table-column property="innerCode" label="机器编号" width="150"></el-table-column>
        <el-table-column property='' label="设备状态" width="150">
          <template #default="{row}"> {{Status(row.vmStatus)}}  </template>
        </el-table-column>
        <el-table-column property="" label="最后一次供货时间">
          <template #default="{row}"> {{Time(row.lastSupplyTime)}}  </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
// import { nodeList, addNode, delNode, viewNode, editNode } from '@/api/point'
import { nodeList, delNode, viewNode, inRegion, inBusiness, inPartner, addNode, editNode } from '@/api/point'
export default {
  data () {
    return {
      options: regionData,
      address_list: [],
      add_address: {
        title: '添加地址',
        name: '',
        tel: '',
        selectedOptions: [],
        addressText: '',
        detailaddress: ''
      },
      searchData: {
        name: '',
        region: ''
      },
      list: [],
      viewList: [],
      drawer: false,
      drawerType: 'add', // add表示添加，views表示预览，edit表示编辑
      regionData: {
        pageIndex: 1,
        pageSize: 10
      },
      name: '',
      total: '', // 总条数
      totalPage: '', // 总页数
      visible: false,
      // 弹出层的信息
      formData: {
        name: '',
        regionId: '', // 所在区域id
        businessId: '', // 所在商圈id
        ownerId: '', // 合作商id
        addr: '', // 详细地址
        areaCode: '', // 区号
        addrtext: '', // 输入地址
        innerCode: '', // 机器编号
        vmStatus: '', // 设备状态
        lastSupplyTime: '', // 最后一次供货时间
        createUserId: 1
      },
      formRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 15, message: '请输入', trigger: 'blur' }
        ],
        regionId: [{ required: true, message: '请输入', trigger: 'blur' }],
        businessId: [{ required: true, message: '请输入', trigger: 'blur' }],
        ownerName: [{ required: true, message: '请输入', trigger: 'blur' }],
        areaCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        addr: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      diaList: [],
      // 弹框select选项内容
      RegionList: [],
      BusinessList: [],
      PartnerList: []
    }
  },
  computed: {
    // 弹框类型
    drawerTitle () {
      let title = '新增点位'
      if (this.drawerType === 'views') title = '点位详情'
      if (this.drawerType === 'edit') title = '修改点位'
      return title
    }
  },
  created () {
    this.getList()
  },
  methods: {

    handleChange (arr) {
      // 此句为el-cascader的值
      const addressText = CodeToText[arr[0]] + CodeToText[arr[1]] + CodeToText[arr[2]]
      console.log(addressText)
      this.add_address.addressText = addressText
    },
    Status (vmStatus) {
      let newVmStatus = '未投放'
      if (vmStatus === 0) newVmStatus = '未投放'
      if (vmStatus === 1) newVmStatus = '运营'
      if (vmStatus === 3) newVmStatus = '撤机'
      return newVmStatus
    },
    Time (lastSupplyTime) {
      return dayjs(lastSupplyTime).format('YYYY.MM.DD HH:mm:ss')
    },
    async onSubmit () {
      console.log(this.searchData)
      // this.name = this.searchName
      // 筛选请求列表数据
      const res = await nodeList({ ...this.regionData, name: this.searchData.name, regionId: this.searchData.region })
      this.list = res.currentPageRecords
      // this.getList()
      console.log(res)
    },
    async openDrawer (type) {
      this.drawerType = type
      this.visible = true
      const { currentPageRecords } = await inRegion({ pageIndex: 1, pageSize: 1000 })
      this.RegionList = currentPageRecords
      // console.log(this.RegionList)
      this.BusinessList = await inBusiness()
      const res = await inPartner({ pageIndex: 1, pageSize: 1000 })
      this.PartnerList = res.currentPageRecords
    },
    // 第一次请求列表数据
    async getList () {
      const res = await nodeList(this.regionData)
      // console.log(res)
      this.list = res.currentPageRecords
      this.total = res.totalCount
      this.totalPage = res.totalPage
    },
    // 上一页
    pre () {
      // console.log('xd')
      if (this.regionData.pageIndex === 1) return
      this.regionData.pageIndex--
      this.getList()
    },
    // 下一页
    next () {
      if (this.regionData.pageIndex >= this.totalPage) return
      this.regionData.pageIndex++
      this.getList()
    },
    // 弹出层关闭事件
    closeFn () {
      this.$refs.diaForm.resetFields()
      this.visible = false
      this.formData = {
        // 手动清空残留数据
        name: '',
        regionId: '', // 所在区域id
        businessId: '', // 所在商圈id
        ownerId: '', // 合作商id
        addr: '', // 详细地址
        areaCode: '', // 区号
        addrtext: '', // 输入地址
        innerCode: '', // 机器编号
        vmStatus: '', // 设备状态
        lastSupplyTime: '', // 最后一次供货时间
        createUserId: 1
      }
    },
    async submit () {
      const area = `${this.formData.areaCode[0]}-${this.formData.areaCode[1]}-${this.formData.areaCode[2]}`
      this.formData.areaCode = `${this.formData.areaCode[0]}/${this.formData.areaCode[1]}/${this.formData.areaCode[2]}`
      // console.log(this.formData.areaCode)
      this.formData.addr = `${area}-${this.formData.addr}`
      console.log(this.formData.addr) // 山西省-长治市-屯留区-ccc
      this.formData.areaCode =
        TextToCode[this.formData.areaCode.split('/')[0]][
          this.formData.areaCode.split('/')[1]
        ][this.formData.areaCode.split('/')[2]].code
      console.log(this.formData.areaCode) // 150523 区号
      const str = this.PartnerList.find(item => {
        if (item.id === this.formData.ownerId) {
          return item
        }
        return item
      })
      this.formData.ownerName = str.name
      console.log(this.formData.ownerName) // 金燕龙合作商
      if (this.drawerType === 'add') {
        await addNode(this.formData)
        this.$message.success('添加成功')
      }
      if (this.drawerType === 'edit') {
        await editNode(this.formData)
        this.$message.success('修改成功')
      }
      this.closeFn()
      this.getList()
    },
    // 删除点位
    async del (id) {
      await delNode(id)
      this.getList()
      this.$message.success('删除成功')
    },
    edit (row) {
      this.openDrawer('edit')
      this.formData = { ...row }
    },
    async views (id) {
      this.diaList = await viewNode(id)
      this.openDrawer('views')
    }
  }
}
</script>

<style lang="scss" scoped>
.search {
  display: flex;
  height: 64px;
  width: 100%;
  -webkit-box-align: center;
  align-items: center;
  margin-bottom: 20px;
  padding-left: 17px;
  background-color: #fff;
  .el-form {
    padding-top: 20px;
  }
}
.result {
  padding: 10px;
  width: 100%;
  background-color: #fff;
  .operation {
    margin-bottom: 20px;
    width: 40px;
    height: 20px;
    .el-button {
      align-items: center;
      width: 80px !important;
      height: 36px;
      padding: 0;
      color: #fff;
      font-size: 16px;
      background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    }
  }
}
.actions {
    font-size: 14px;
    display: flex;
    justify-content: space-around;
    color: #666;
    .red {
      color: red;
    }
}
.footer {
    display: flex;
    width: 100%;
    padding: 20px 10px;
    justify-content: space-between;
    .text {
      margin-right: 10px;
      font-size: 18px;
      color: #dde1e7;
    }
    .btn {
      button {
        padding: 5px 10px;
        margin-right: 10px;
      }
    }
  }
.dialog-footer {
  width: 100%;
  display: inline-block;
  text-align: center;
  .el-button--primary {
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  }
}
.fr {
  float: right;
  display: flex;
  justify-content: space-between;
  width: 300px;
}
.fl {
  float: left;
}
.prePage {
  padding-right: 20px;
}
</style>
